package com.ruoyi.ichen.rabbitmq;

import com.rabbitmq.client.*;
import com.ruoyi.ichen.rabbitmq.common.RabbitMQUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.xml.ws.Service;
import java.io.IOException;

/**
 * @author ichen
 * @version V1.0
 * @ClassName: Customer
 * @Description: rabbitmq消费者
 * @Date 2020/7/26 13:31
 */
public class Customer2 {

    @Autowired
    private Service service;

    public static void main(String[] args) {
        try {
            //获取连接对象
            Connection connection = RabbitMQUtils.getConnection();
            //获取连接通道
            Channel channel = connection.createChannel();
            channel.basicQos(1);//每次只能消费一个消息

            channel.queueDeclare("hello", false, false, false, null);
            //参数1:队列名称 参数2:消息自动确认 true 消费者自动向rabbitmq确认消息, false 不会自动确认消息
            channel.basicConsume("hello", false, new DefaultConsumer(channel) {
                @Override // 最后一个参数 消息队列中取出的消息
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("消费者-1: " + new String(body));
                    //参数1:确认队列中那个具体消息 参数2:是否开启多个消息同时确认
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
